﻿# ui/web_view.py
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtCore import QObject, pyqtSlot

class ChartBridge(QObject):
    @pyqtSlot(str)
    def debug(self, msg):
        print("JS:", msg)

def create_web_view():
    """返回一个支持QWebChannel的QWebEngineView"""
    view = QWebEngineView()
    channel = QWebChannel()
    bridge = ChartBridge()
    channel.registerObject("pyBridge", bridge)
    view.page().setWebChannel(channel)

    html = """
    <html>
    <head>
        <script src="https://cdn.plot.ly/plotly-2.27.0.min.js"></script>
        <script>
            new QWebChannel(qt.webChannelTransport, function(channel) {
                window.pyBridge = channel.objects.pyBridge;
                Plotly.newPlot('chart', [], {
                    title: '等待数据...',
                    template: 'plotly_dark',
                    height: 600
                }, {responsive: true});
            });

            function updateKline(jsonData) {
                try {
                    var data = JSON.parse(jsonData);
                    Plotly.react('chart', data.traces, data.layout);
                } catch(e) {
                    console.error("Update failed:", e);
                }
            }
        </script>
    </head>
    <body style="margin:0;padding:0;background:#1e1e1e;color:#fff;font-family:Arial">
        <div id="chart" style="width:100%;height:600px;"></div>
    </body>
    </html>
    """
    view.setHtml(html)
    return view